package com.bruce.starts.demo.commonerror.transaction.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import java.util.List;
import java.util.Map;

@Service
public class DefaultThreadExecutionService implements ThreadExecutionService {
    private static final Logger logger = LoggerFactory.getLogger(DefaultThreadExecutionService.class);
    @Autowired
    private PlatformTransactionManager transactionManager;

    @Override
    public int executeBatch(ThreadExecution threadExecution, List sequence, Map<Long, TransactionStatus> longTransactionStatusMap, BatchTransactionInfo info) {
        synchronized (info) {
            TransactionStatus transactionStatus = transactionManager.getTransaction(TransactionDefinition.withDefaults());
            longTransactionStatusMap.put(Thread.currentThread().getId(), transactionStatus);
            try {
                threadExecution.excute(sequence);
                info.getSuccessThreads().incrementAndGet();
            } finally {
                info.getCompleteThreads().incrementAndGet();
                if (logger.isInfoEnabled()) {
                    logger.info("完成任务：" + Thread.currentThread().getName());
                }
            }
        }
        return 1;
    }
}
